import json
import re
import os
import time

import ipfshttpclient

ipfsApi = os.environ.get('IPFS_API')

api = ipfshttpclient.connect(ipfsApi, timeout=3600)

root = api.files.ls('/')
res = []
for key1 in root['Entries']:
    temp = root = api.files.ls('/'+ key1['Name'])
    for key2 in temp['Entries']:
        filesHash = api.files.stat('/'+key1['Name']+'/'+key2['Name']+'/files.json')
        filesJson = api.cat(filesHash['Hash'])
        info = json.loads(filesJson)
        label = []
        for file in info['files']:
            for stream in file["mediainfo"]['streams']:
                if stream["codec_type"] in ["audio","video"]:
                    if stream["codec_name"] == "h264":
                        if 'H264' not in label:
                            label.append('H264')
                    elif stream["codec_name"] == "hevc":
                        if 'H265' not in label:
                            label.append('H265')
                    elif stream["codec_name"] == "aac":
                        if 'aac' not in label:
                            label.append('aac')
        res.append({
          "id": key2['Name'],
          "title": info['title'],
          "tags": label,
          "filesHash": '/ipfs/'+filesHash['Hash'],
        })
print("load "+ str(len(res))+ " items.")
out = {
  "createTime": round(time.time()),
  "data": res
}
json_file = os.path.join('/data/', 'data.json')
file = open(json_file, 'w')
json.dump(out, file, ensure_ascii=False)
file.close()
